package cloudPayAdmin.admin.controller.hicatcard.user;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.project.m.api.common.biz.resp.BizResp;

import cloudPayAdmin.admin.dbapp.entity.hicatcard.card.TCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUser;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserCard;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserPlan;
import cloudPayAdmin.admin.dbapp.entity.hicatcard.user.TUserThird;
import cloudPayAdmin.admin.dbapp.vo.hicatcard.VCardCoupon;
import cloudPayAdmin.admin.dbapp.vo.hicatcard.VUserThird;
import cloudPayAdmin.admin.service.hicatcard.user.UserService;
import cloudPayAdmin.admin.service.hicatcard.user.UserThirdService;
import cloudPayAdmin.constant.BusiError;
import cloudPayAdmin.constant.Constant;
import cloudPayAdmin.util.AdminLteDataTableResp;
import cloudPayAdmin.util.AdminLteUtil;
import cloudPayAdmin.util.HttpUtil;
import cloudPayAdmin.util.TimeUtil;
import cloudPayAdmin.util.WebUtil;
import cloudPayAdmin.util.WxApiUtil;
import cloudPayAdmin.util.ZipUtil;
import cloudPayAdmin.util.pagebean.HqlPageBeanHelper;
import cloudPayAdmin.util.pagebean.HqlParam;
import cloudPayAdmin.util.pagebean.PageBean;

@Controller
@RequestMapping("/hicatcard/userThird")
public class UserThirdController {
	
	@Autowired
	UserThirdService userThirdService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	HqlPageBeanHelper hqlPageBeanHelper;

	@PersistenceContext(unitName = "entityManagerFactory")
	EntityManager entityManager;
	
	@Autowired
	Environment env;
	
	@RequestMapping(value = "/toUserThirdListPage")
	public String toListPage(HttpServletRequest request, Map<String, Object> model) {
		//request.setAttribute("typeMap", TUserThird.initTypeMap());
		
		/*List<TUserPlan> userPlanList = userThirdService.findUserPlanByType(TUserThird.TYPE_RENBAO);
		if(CollectionUtils.isNotEmpty(userPlanList)) {
			request.setAttribute("TUserPlan", userPlanList.get(0));
		}*/
		
		return "hicatcard/user/user-third-list";
	}
	
	@RequestMapping("/getUserThirdListData")
	@ResponseBody
	public String getUserThirdListData(HttpServletRequest request) {
		Map<String, Object> paramMap = WebUtil.getSearchParam(request);
		paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
		// 需要映射的实体类
		HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, VUserThird.class, request);
		PageBean<VUserThird> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);
		
		for(VUserThird userThird : cloudpayCardPage.getContent()) {
			
			String qrCodePath = StringUtils.contains(userThird.getQrPath(), env.getProperty("image.upload.database.suffix.path")) ? userThird.getQrPath() : env.getProperty("image.upload.database.suffix.path") + userThird.getQrPath();
			userThird.setQrPath(env.getProperty("image.http.base.path") + qrCodePath);
			
		}
		
		
		AdminLteDataTableResp<VUserThird> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage,request);
		return resp.toAdminLteJsonString(VUserThird.class);
	}
	
	
	@RequestMapping("/toBatchMakeUserThirdPage")	
	public String toBatchMakeCardPage(HttpServletRequest request) {
		
		List<TUserPlan> userPlanList = userThirdService.findUserPlanByType(TUserThird.TYPE_RENBAO);
		
		if(CollectionUtils.isNotEmpty(userPlanList)) {
			String maxAccountId = userThirdService.getMaxAccountId();
			if(StringUtils.isEmpty(maxAccountId)) {
				maxAccountId = "00000";
			}
			
			/* else {
				maxAccountId = StringUtils.replace(maxAccountId, userPlanList.get(0).getPrefix(), "");
			}*/
			
			request.setAttribute("maxAccountId", String.valueOf(Integer.parseInt(maxAccountId) + 1));
		}
	
		return "hicatcard/user/batch-make-user-third";
	}
	
	@RequestMapping("/batchMakeUserThird")
	@ResponseBody
	public String batchMakeUserThird(HttpServletRequest request,String beginIdStr,Integer amount,String prefix) throws Exception {
		
		BizResp resp = new BizResp();
		
		Long beginId = Long.parseLong(beginIdStr);
		Long anoBeginId = beginId;
		
		List<String> accountIds = new ArrayList<String>();
		for(int i=0;i<amount;i++) {
			
			String temAccountId = "00000" + anoBeginId;
			String accountId = prefix + StringUtils.substring(temAccountId, temAccountId.length() - 5);
			accountIds.add(accountId);
			
			anoBeginId = anoBeginId + 1;
		}
		
		List<TUserThird> userThirdsList = userThirdService.findUserThirdByAccountIds(accountIds);
		
		if(CollectionUtils.isNotEmpty(userThirdsList)) {
			resp.setResult_code("201110");
			resp.setError_message("id号重复,请重新填写");
			return JSON.toJSONString(resp);
		}
		
		Integer maxBatch = userThirdService.getMaxBatch();
		Integer nowBatch = null;
		if(maxBatch == null) {
			nowBatch = 1;
		} else {
			nowBatch = maxBatch + 1;
		}
		
	//	List<TUserPlan> userPlanList = userThirdService.findUserPlanByType(TUserThird.TYPE_RENBAO);
	//	String prefix = userPlanList.get(0).getPrefix();
		
		List<String> qrCodeFiles = new ArrayList<String>();
		List<String> zipEntryNames = new ArrayList<String>();
		List<TUserThird> userThirdList = new ArrayList<TUserThird>();
		
		for(int i=0;i<amount;i++) {
			TUserThird uesrThird = new TUserThird();
			uesrThird.setType(TUserThird.TYPE_RENBAO);
			String temAccountId = "00000" + beginId;
			String accountId = prefix + StringUtils.substring(temAccountId, temAccountId.length() - 5);
			uesrThird.setAccountId(accountId);
			uesrThird.setStatus(TUserThird.STATUS_NOT_USE);
			uesrThird.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			uesrThird.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
			uesrThird.setBatch(nowBatch);
			
			String databasePath = env.getProperty("image.upload.database.suffix.path") + Constant.USERTHIRD_PIC_FILE_PATH + HttpUtil.HTTP_PATH_SEPERATOR + accountId + "_" + System.nanoTime() + ".png";
			String destinationPath = env.getProperty("image.upload.base.path") + StringUtils.replaceEach(databasePath, new String[]{env.getProperty("image.upload.database.suffix.path"),HttpUtil.HTTP_PATH_SEPERATOR}, new String[]{"",File.separator});
			FileUtils.copyInputStreamToFile(WxApiUtil.getUnLimitQrCode(accountId, "pages/card-detail/index"), new File(destinationPath));
			
			uesrThird.setQrPath(databasePath);
			
			userThirdList.add(uesrThird);
			
			beginId ++ ;
			
			qrCodeFiles.add(destinationPath);
			zipEntryNames.add(accountId + ".png");
		}
		
		userThirdService.saveUserThird(userThirdList,prefix);
		
		String zipFileName = Constant.USERTHIRD_PIC_FILE_PATH + File.separator + TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR) + "_" + qrCodeFiles.size() + ".zip";
		String zipPath = env.getProperty("image.upload.base.path") + zipFileName;
		ZipUtil.toZipByFilePaths(qrCodeFiles, zipEntryNames, new FileOutputStream(new File(zipPath)));
		
		String downloadUrl = env.getProperty("image.http.base.path") + env.getProperty("image.upload.database.suffix.path") + StringUtils.replace(zipFileName, File.separator, "/");
		
		resp.setResult_code(BusiError.ERR_CODE_SUCCESS);
		resp.setError_message(downloadUrl);
		return JSON.toJSONString(resp);
	}
	
}
